package Prova::Controller::Tags;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Data::Dumper;

=head1 NAME

Prova::Controller::Tags - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 create

create action

=cut

sub create : Private {
    my ( $self, $c, $name ) = @_;

    $c->log->debug("=== tags :  ".Dumper $name);
    my $tag = $c->model( 'DBIC::Tags' )->create( {
                                                  name => $name,
                                                  checksum => Prova::Checksum->calc( $name ),
                                                  order_by => $self->max_order_by( $c ) + 1
                                              } );
    return $tag;
}

=head2 find_by_name

get tags models having name

=cut

sub find_by_name : Private {
    my ( $self, $c, $name ) = @_;

    my ( $tag ) = $c->model( 'DBIC::Tags' )->search(
        { name => $name }
    );

    return $tag;
}

=head2 get_tags

get tags action

=cut

sub get_tags : Private {
    my ( $self, $c, $names ) = @_;

    my %where;
    $where{name} = $names if ref $names;
    my @tags = $c->model( 'DBIC::Tags' )->search( \%where );
    return \@tags;
}

=head2 get_tags_name

get tags names action

=cut

sub get_tags_name : Private {
    my ( $self, $c ) = @_;
    my $tags = $self->get_tags( $c );
    return [ sort map{ $_->name } @$tags ];
}

=head2 max_order_by

get max order_by action

=cut

sub max_order_by {
    my ( $self, $c ) = @_;

    my ($tag) = $c->model('DBIC::Tags')->search(
                                                         {},
                                                         {order_by => 'order_by desc',
                                                          limit => 1}
                                                     )->first;
    return $tag ? $tag->order_by : 0;
}

=head1 AUTHOR

Shanon Inc, E<lt>http://www.shanon.co.jp/E<gt>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
